package com.ajk.server.bkcontroller;

import java.security.Principal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.SetUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.ajk.server.exception.AjkException;
import com.ajk.server.exception.ErrorConstant;
import com.ajk.server.model.request.CategoryReq;
import com.ajk.server.model.request.ShopGoodsReq;
import com.ajk.server.model.response.Result;
import com.ajk.server.model.response.ResultList;
import com.ajk.server.model.response.ResultObject;
import com.ajk.server.service.UsersService;
import com.ajk.server.utils.FileStoreUtil;
import com.ajk.server.utils.IntegerUtil;
import com.ajk.shop.model.Category;
import com.ajk.shop.model.Goods;
import com.ajk.shop.model.GoodsCategory;
import com.ajk.shop.model.GoodsImage;
import com.ajk.shop.model.request.GoodsReq;
import com.ajk.shop.model.request.OrderInfoReq;
import com.ajk.shop.model.response.CategoryRes;
import com.ajk.shop.model.response.GoodsRes;
import com.ajk.shop.model.response.OrderInfoRes;
import com.ajk.shop.model.response.SimpleUserProfileRes;
import com.ajk.shop.service.GoodsService;
import com.ajk.shop.service.OrderService;

@RestController
@RequestMapping("/admin/shop")
public class AdminShopController {
	
	private final static Logger logger = LoggerFactory.getLogger(AdminShopController.class);
	
	@Autowired
	private GoodsService goodsService;
	
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private UsersService usersService;
	
	/**
	 * 分类列表
	 * @param category
	 * @return
	 */
	@RequestMapping(value="/category/list",method=RequestMethod.GET)
	public ResultList<CategoryRes> categoryList(Category category){
		List<CategoryRes> list = goodsService.categoryList();
		return new ResultList<CategoryRes>(list);
	}
	/**
	 * 添加分类
	 * @param category
	 * @return
	 */
	@RequestMapping(value="/category/add",method=RequestMethod.POST)
	public Result categoryAdd(@RequestBody Category category){
		goodsService.categoryAdd(category);
		return new Result();
	}
	/**
	 * 更新分类
	 * @param category
	 * @return
	 */
	@RequestMapping(value="/category/update",method=RequestMethod.PUT)
	public Result categoryUpdate(@RequestBody Category category){
		goodsService.categoryUpdate(category);
		return new Result();
	}
	
	/**
	 * 删除分类
	 * @return
	 */
	@RequestMapping(value="/category/delete/{id}",method=RequestMethod.DELETE)
	public Result categoryDelete(@PathVariable("id") Integer id){
		if(id == null || id == 0){
			throw new AjkException(ErrorConstant.PARAM_ERROR.getErrorCode(), "分类ID不能为空");
		}
		Category category = new Category();
		category.setId(id);
		goodsService.categoryDelete(category);
		return new Result();
	}
	
	/**
	 * 删除分类
	 * @param category
	 * @return
	 */
	@RequestMapping(value="/category/set_home_view/{id}/{recommend}",method=RequestMethod.PUT)
	public Result categoryHomeView(@PathVariable("id") Integer id,@PathVariable("recommend") Integer recommend){
		if(id == null || id == 0){
			throw new AjkException(ErrorConstant.PARAM_ERROR.getErrorCode(), "分类ID不能为空");
		}
		if(recommend == null){
			throw new AjkException(ErrorConstant.PARAM_ERROR.getErrorCode(), "recommend 不能为空");
		}
		Category category = new Category();
		category.setId(id);
		category.setRecommend(recommend);
		goodsService.categoryHomeView(category);
		return new Result();
	}
	
	/**
	 * 设置在banner展示
	 * @param categoryReq
	 * @return
	 */
	@RequestMapping(value="/category/set_banner_view",method = RequestMethod.POST, consumes = "multipart/form-data")
	public Result categoryBannerView(Category category , MultipartFile imageFile){
//		Category category = categoryReq.toCategory();
		//MultipartFile imageFile = categoryReq.getImageFile();

		if(category.getId() == null){
			throw new AjkException(ErrorConstant.PARAM_ERROR.getErrorCode(), "分类ID不能为空");
		}
		if(category.getRecommend() == null){
			throw new AjkException(ErrorConstant.PARAM_ERROR.getErrorCode(), "recommend 不能为空");
		}
		if(category.getRecommend() == 1){
			category.setRecommend(2);
			if(imageFile!=null && imageFile.getSize()>0){
				logger.info("文件大小 {}",imageFile.getSize());
				if (imageFile.getSize() > 2097152) {
					throw new AjkException(ErrorConstant.PARAM_ERROR.getErrorCode(), "文件太大,请选择小于2兆的文件上传");
				}
				String fileDbName = FileStoreUtil.storeFile(imageFile, "shop/category");
				category.setImage(fileDbName);
			} else {
				// 文件传输失败。抛异常
				throw new AjkException(ErrorConstant.PARAM_ERROR.getErrorCode(), "文件传输失败！请重试");
			}
		}else{
			category.setRecommend(0);
		}
		goodsService.categoryBannerView(category);
		return new Result();
	}

	
	/**
	 * 商品详情
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/goods/detail/{id}")
	public ResultObject<GoodsRes> goodsDetail(@PathVariable("id") Integer id){
		GoodsReq gr = new GoodsReq();
		gr.setId(id);
		GoodsRes goodsRes = goodsService.goodsDetail(gr);
		
		return new ResultObject<GoodsRes>(goodsRes);
	}
	
	
	/**
	 * 商品详情
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/goods/list")
	public ResultList<GoodsRes> goodsList(GoodsReq goodsReq){
		if(goodsReq.getLimit() == null || goodsReq.getLimit() <= 0){
			throw new AjkException(ErrorConstant.PARAM_ERROR.getErrorCode(), "limit 不能为空");
		}
		List<GoodsRes> goodsRes = goodsService.goodsList(goodsReq);
		ResultList<GoodsRes> result = new ResultList<GoodsRes>(goodsRes);
		result.setExt(goodsService.goodsListCount(goodsReq));
		return result;
	}
	
	@RequestMapping(method = RequestMethod.POST, consumes = "multipart/form-data",value="/goods/add")
	public ResultObject<Integer> addGoods(ShopGoodsReq req){
		req.setThumbnailImage(null);
		req.setAddGoodsImagePaths(null);
		
		req.dealWith();
		
		//存储小图
			//在dealWith中做了
		//新增
		Goods gg = req.toGoods();
		Integer goodsId = goodsService.insertGoods(gg);
		
		//存储商品图片
		if (CollectionUtils.isNotEmpty(req.getAddGoodsImagePaths())) {
			for (String path : req.getAddGoodsImagePaths()) {
				GoodsImage goodsImage = new GoodsImage();
				goodsImage.setGoodsId(goodsId);
				goodsImage.setStatus(1);
			//	goodsImage.setImageSmall(path); 目前前端只用setImageLarge
				goodsImage.setImageLarge(path);
				
				goodsService.insertGoodsImage(goodsImage);
			}
		}
		
		// 添加分类
		if (CollectionUtils.isNotEmpty(req.getCategoryIdList())) {
			for (Integer categoryId : req.getCategoryIdList()) {
				GoodsCategory goodsCategory = new GoodsCategory();
				goodsCategory.setCategoryId(categoryId);
				goodsCategory.setGoodsId(goodsId);
				goodsService.insertGoodsCategory(goodsCategory);
			}
		}
		
		return new ResultObject<Integer>(goodsId);
	}
	
	@RequestMapping(method = RequestMethod.POST, consumes = "multipart/form-data",value="/goods/modify")
	public ResultObject<Integer> modifyGoods(ShopGoodsReq req){
		req.setThumbnailImage(null);
		req.setAddGoodsImagePaths(null);
		
		req.dealWith();
		
		Integer goodsId = req.getId();
		if(!IntegerUtil.isPositiveInteger(goodsId)){
			throw new AjkException(ErrorConstant.OPERATION_ERROR.getErrorCode(), "商品ID不能为空");
		}

		//存储小图
			//在dealWith中做了
		//新增
		Goods gg = req.toGoods();
		goodsService.updateGoods(gg);
		
		//存储商品图片
		if (CollectionUtils.isNotEmpty(req.getAddGoodsImagePaths())) {
			for (String path : req.getAddGoodsImagePaths()) {
				GoodsImage goodsImage = new GoodsImage();
				goodsImage.setGoodsId(goodsId);
				goodsImage.setStatus(1);
			//	goodsImage.setImageSmall(path); 目前前端只用setImageLarge
				goodsImage.setImageLarge(path);
				
				goodsService.insertGoodsImage(goodsImage);
			}
		}
		
		//修改商品图片
		if (CollectionUtils.isNotEmpty(req.getModifyGoodsImageList())) {
			for (GoodsImage gImage : req.getModifyGoodsImageList()) {
				gImage.setGoodsId(goodsId);
				gImage.setImageLarge(null);
				
				goodsService.updateGoodsImage(gImage);
			}
		}
		
		List<GoodsCategory> goodsCategories = goodsService.findGoodsCategoryByGoodsId(goodsId);
		Map<Integer, GoodsCategory> map = new HashMap<Integer, GoodsCategory>();	
		if (CollectionUtils.isNotEmpty(goodsCategories)) {
			for (GoodsCategory goodsCategory : goodsCategories) {
				map.put(goodsCategory.getCategoryId(), goodsCategory);
			}
		}
		
		// 添加分类
		if (CollectionUtils.isNotEmpty(req.getCategoryIdList())) {
			Set<Integer> set = new HashSet<>();
			set.addAll(req.getCategoryIdList());
			
			//数据库中比传入的多
			Set<Integer> deletes = SetUtils.difference(map.keySet(), set);
			Set<Integer> adds = SetUtils.difference(set,map.keySet());
			
			//删除分类
			if (CollectionUtils.isNotEmpty(deletes)) {
				for (Integer integer : deletes) {
					GoodsCategory category = map.get(integer);
					if(category!=null){
						goodsService.deleteGoodsCategory(category.getId());
					}
				}
			}
			
			// 添加分类
			if (CollectionUtils.isNotEmpty(adds)) {
				for (Integer categoryId : adds) {
					GoodsCategory goodsCategory = new GoodsCategory();
					goodsCategory.setCategoryId(categoryId);
					goodsCategory.setGoodsId(goodsId);
					goodsService.insertGoodsCategory(goodsCategory);
				}
			}
		}
		
		return new ResultObject<Integer>(goodsId);
	}
	
	/**
	 * 订单列表
	 * @param principal
	 * @param orderInfoReq
	 * @return
	 */
	@RequestMapping(value="/order/list",method=RequestMethod.GET)
	public ResultList<OrderInfoRes> orderMyList(Principal principal,OrderInfoReq orderInfoReq){
		ResultList<OrderInfoRes> resultList = new ResultList<OrderInfoRes>();
		List<OrderInfoRes> infoRes = orderService.orderLisr(orderInfoReq);
		if (CollectionUtils.isNotEmpty(infoRes)) {
			Set<Integer> userIds = new HashSet<>();
			for (OrderInfoRes orderInfoRes : infoRes) {
				userIds.add(orderInfoRes.getUserId());
			}
			List<SimpleUserProfileRes> users = usersService.findSimpleUsersByIds(new ArrayList<>(userIds));
			if (CollectionUtils.isNotEmpty(users)) {
				Map<Integer, SimpleUserProfileRes> map = new HashMap<>();
				for (SimpleUserProfileRes simpleUserProfileRes : users) {
					map.put(simpleUserProfileRes.getUserId(), simpleUserProfileRes);
				}
				
				for (OrderInfoRes orderInfoRes : infoRes) {
					orderInfoRes.setUser(map.get(orderInfoRes.getUserId()));
				}
			}
		}
		resultList.setItemList(infoRes);
		resultList.setExt(orderService.orderLisrCount(orderInfoReq));
		return resultList;
	}

	/**
	 * 订单详情
	 * @param principal
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/order/detail/{id}",method=RequestMethod.GET)
	public ResultObject<OrderInfoRes> orderDetail(Principal principal,@PathVariable("id") Integer id){
		if(null == id || id <= 0){
			throw new AjkException(ErrorConstant.PARAM_ERROR.getErrorCode(), "订单ID不能为空");
		}
		ResultObject<OrderInfoRes> resultObject = new ResultObject<OrderInfoRes>();
		OrderInfoReq orderInfoReq = new OrderInfoReq();
//		orderInfoReq.setUserId(userDetails.getUserId());
		orderInfoReq.setId(id);
		
		OrderInfoRes res = orderService.orderDetail(orderInfoReq);
		
		Integer userId = res.getUserId();
		
		SimpleUserProfileRes userProfileRes = usersService.findSimpleUsersById(userId);
		
		res.setUser(userProfileRes);
		
		resultObject.setDomain(res);
		return resultObject;
	}
	
	/**
	 * 订单运单补充
	 * @param principal
	 * @param orderInfoReq
	 * @return
	 */
	@RequestMapping(value="/order/shipping_order",method=RequestMethod.PUT)
	public ResultObject<Integer> shippingOrder(Principal principal,@RequestBody OrderInfoReq orderInfoReq){
		ResultObject<Integer> resultObject = new ResultObject<Integer>();
		
		Integer id = orderInfoReq.getId();
		Integer shippingChannel = orderInfoReq.getShippingChannel();
		String shiippingSn = orderInfoReq.getShiippingSn();
		Integer shippingStatus = 1; //0 未发货 1.已发货 2.已收货
		Date shippingTime = new Date();
		
		OrderInfoReq req = new OrderInfoReq();
		req.setId(id);
		req.setShiippingSn(shiippingSn);
		req.setShippingChannel(shippingChannel);
		req.setShippingStatus(shippingStatus);
		req.setShippingTime(shippingTime);
		
		Integer count = orderService.shippingOrder(req);
		
		resultObject.setDomain(count);
		
		return resultObject;
	}
	
}